package cc.vv.baselibrary.util;

import android.text.TextUtils;

import java.util.ArrayList;

/**
 * String字符串处理工具类
 * Created by sun.li on 2017/7/18.
 */

public class StringProcessingUtil {

    /**
     * 去除字符串中的空格
     */
    public static String stringRemoveBlankSpace(String str) {
        if (!TextUtils.isEmpty(str)) {
            str = str.replace(" ", "");
        }
        return str;
    }

    /**
     * 格式化显示的电话号码
     *
     * @param num
     * @return
     */
    public static String setNumFormat(String num) {// &#160
        if (TextUtils.isEmpty(num)) {
            return "";
        }
        if (FormatUtil.isMobileNO(num)) {
            String maskNumber = num.substring(0, 3) + "****" + num.substring(7, 11);
            return maskNumber;
        } else {
            return num;
        }
    }

    /**
     * Html非法字符过滤
     *
     * @param htmlContent
     * @return
     */
    public static String htmlIllegalCharacterFiltering(String htmlContent) {// &#160
        if (TextUtils.isEmpty(htmlContent)) {
            return "";
        }
        /* 图片无法点击放大问题适配处理*/
        htmlContent = htmlContent.replace(" alt", " title");
        /* 屏蔽a链接点击跳转功能适配*/
        htmlContent = htmlContent.replace(" href", " name");
        /* center过时标签适配替换*/
        htmlContent = htmlContent.replace("<center ", "<p ");
        htmlContent = htmlContent.replace("</center>", "</p>");
        /* 过滤缩进*/
        htmlContent = htmlContent.replace(" text-indent", " title");

        return htmlContent;
    }

    /**
     * 计算webView中图片的url集合
     *
     * @param originH5Content 图片H5数据
     */
    public static ArrayList<String> getImgUrls(String originH5Content) {
        ArrayList<String> imgUrlList = new ArrayList<>();
        if (TextUtils.isEmpty(originH5Content)) {
            return imgUrlList;
        }
        while (originH5Content.contains("<img")) {
            originH5Content = splitImgData(imgUrlList, originH5Content);
        }
        return imgUrlList;
    }

    /**
     * 重复分割图片url
     */
    private static String splitImgData(ArrayList<String> imgUrlList, String originImgContent) {
        if (TextUtils.isEmpty(originImgContent) || imgUrlList == null) {
            return originImgContent;
        }
        String imgH5 = originImgContent.substring(originImgContent.indexOf("<img"));
        String imgSrc = imgH5.substring(imgH5.indexOf("src=\"") + "src=\"".length());
        String imgUrl = imgSrc.substring(0, imgSrc.indexOf("\""));
        imgUrlList.add(imgUrl);
        String end = imgSrc.substring(imgSrc.indexOf("\"") + "\"".length());
        return end;
    }
}
